﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Read.Applications.Commands.User;
using AuthCenter_API.Read.Architecture.Common;
using AuthCenter_API.Read.Dtos;
using MediatR;

namespace AuthCenter_API.Read.Applications.CommandHandlers.User
{
    public class UserLoginCommandHandler : IRequestHandler<UserLoginCommand, APIResult<object>>
    {
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IBaseRepository<UserRoleModel> _userrole;
        private readonly JwtTools jwtTools;
        private readonly IConfiguration _configuration;
        public UserLoginCommandHandler(IBaseRepository<UserModel> userRepository, IBaseRepository<UserRoleModel> userrole, JwtTools jwtTools, IConfiguration configuration)
        {
            _userRepository = userRepository;
            _userrole = userrole;
            this.jwtTools = jwtTools;
            _configuration = configuration;
        }

        public Task<APIResult<object>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.LoginSuccess;
            result.Message = APIEnum.LoginSuccess.Desc();
            var m = _userRepository.GetAll().FirstOrDefault(x => x.UserName == request.UserName);
            if (m == null)
            {
                result.Code = APIEnum.LoginFail;
                result.Message = APIEnum.LoginFail.Desc() + "用户名不能为空";
                return Task.FromResult(result);
            }
            if (m.Password != request.Password)
            {
                result.Code = APIEnum.LoginFail;
                result.Message = APIEnum.LoginFail.Desc() + "用户名密码不匹配";
                return Task.FromResult(result);
            }
            List<int> roleid = _userrole.GetAll().Where(x => x.UserId == m.Id).Select(x => x.RoleId).ToList();

            result.Data = new
            {
                m,
                roleid
            };
            result.Token = jwtTools.JwtNewString(_configuration, m.Id.ToString());
            return Task.FromResult(result);
        }
    }
}